package com.example.oa;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class PseudoSignInFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String uri = httpServletRequest.getRequestURI();


        String action = httpServletRequest.getParameter("action");
        if(action != null && action.equals("sign_in")){
            String referer = httpServletRequest.getHeader("Referer");
            if(!referer.contains("index.jsp")){
                httpServletRequest.setAttribute("message", "CORS login");
                httpServletRequest.getRequestDispatcher("/OA/index.jsp").forward(httpServletRequest, httpServletResponse);
            }
        }


        if (uri.contains("admin")) {
            int role = -1;
            if (httpServletRequest.getSession().getAttribute("roleId") != null) {
                role = (int) httpServletRequest.getSession().getAttribute("roleId");
            }
            if (role != 1) {
                httpServletRequest.setAttribute("message", "Invalid visit.");
                httpServletRequest.getRequestDispatcher("/OA/index.jsp").forward(httpServletRequest, httpServletResponse);
            }
        }
        chain.doFilter(request ,response);
    }
}
